//
//  PerfectContentView.m
//  SHHCPhone
//
//  Created by sheng long on 14-6-18.
//  Copyright (c) 2014年 sheng long. All rights reserved.
//

#import "PerfectContentView.h"
#import "NationClass.h"

@interface PerfectContentView()

@end

@implementation PerfectContentView

@synthesize delegate;
@synthesize UIVC;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        mainScroll = [[UIScrollView alloc] initWithFrame:self.bounds];
        [mainScroll setBackgroundColor:[UIColor clearColor]];
        [self addSubview:mainScroll];
        [mainScroll setShowsHorizontalScrollIndicator:NO];
        [mainScroll setShowsVerticalScrollIndicator:NO];
        [mainScroll setBounces:NO];
        
        UIButton *bgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [bgButton setFrame:mainScroll.bounds];
        [mainScroll addSubview:bgButton];
        [bgButton addTarget:self action:@selector(bgButt) forControlEvents:UIControlEventTouchUpInside];
        
        headButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [headButton setImage:[UIImage imageNamed:@"完善资料页-上传头像按钮.png"] forState:UIControlStateNormal];
        [headButton setImage:[UIImage imageNamed:@"完善资料页-上传头像按钮-点击.png"] forState:UIControlStateHighlighted];
        [headButton sizeToFit];
        [mainScroll addSubview:headButton];
        [headButton addTarget:self action:@selector(upHeadButt) forControlEvents:UIControlEventTouchUpInside];
        [headButton setCenter:CGPointMake(mainScroll.frame.size.width/2, 16+headButton.frame.size.height/2)];
        
        UILabel *label1 = [[UILabel alloc] init];
        [label1 setText:@"上传头像"];
        [label1 setTextColor:GET_COLOR(@"ababab")];
        [label1 setBackgroundColor:[UIColor clearColor]];
        [mainScroll addSubview:label1];
        [label1 setFont:[UIFont boldSystemFontOfSize:13]];
        [label1 sizeToFit];
        [label1 setCenter:CGPointMake(self.frame.size.width/2, headButton.frame.size.height+headButton.frame.origin.y+6+label1.frame.size.height/2)];
        
        field1 = [[TextFieldView alloc] init];
        [field1 setBgImage:@"输入框.png" titleImage:@"完善资料页-用户名icon.png" tip:@"昵称"];
        [mainScroll addSubview:field1];
        [field1.textField setDelegate:self];
        [field1.textField setReturnKeyType:UIReturnKeyDone];
        [field1.textField addTarget:self action:@selector(bgButt) forControlEvents:UIControlEventEditingDidEndOnExit];
        [field1 setCenter:CGPointMake(label1.center.x, label1.frame.size.height+label1.frame.origin.y+22+field1.frame.size.height/2)];
        
        //选择出生日期
        field2 = [[TextFieldView alloc] init];
        [field2 setBgImage:@"输入框.png" titleImage:@"完善资料页-出生日期icon.png" tip:@"出生日期"];
        [mainScroll addSubview:field2];
        [field2 setCenter:CGPointMake(label1.center.x, field1.frame.size.height+field1.frame.origin.y+10+field2.frame.size.height/2)];
        
        UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
        [button3 setFrame:field2.frame];
        [mainScroll addSubview:button3];
        [button3 addTarget:self action:@selector(selectCSRQ) forControlEvents:UIControlEventTouchUpInside];
        
        //选择身高
        field3 = [[TextFieldView alloc] init];
        [field3 setBgImage:@"输入框.png" titleImage:@"完善资料页-身高icon.png" tip:@"身高"];
        [mainScroll addSubview:field3];
        [field3 setCenter:CGPointMake(label1.center.x, field2.frame.size.height+field2.frame.origin.y+10+field3.frame.size.height/2)];
        
        UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
        [button4 setFrame:field3.frame];
        [mainScroll addSubview:button4];
        [button4 addTarget:self action:@selector(selectSG) forControlEvents:UIControlEventTouchUpInside];
        
        //选择民族
        field4 = [[TextFieldView alloc] init];
        [field4 setBgImage:@"输入框.png" titleImage:@"完善资料页-民族icon.png" tip:@"选择民族"];
        [mainScroll addSubview:field4];
        [field4 setCenter:CGPointMake(label1.center.x, field3.frame.size.height+field3.frame.origin.y+10+field4.frame.size.height/2)];
        
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [button1 setFrame:field4.frame];
        [mainScroll addSubview:button1];
        [button1 addTarget:self action:@selector(selectMZ) forControlEvents:UIControlEventTouchUpInside];
        
        //选择运动量
        seletView1 = [[PerfectSelectView alloc] initWithFrame:CGRectMake(field4.frame.origin.x, field4.frame.origin.y+5+field4.frame.size.height, mainScroll.frame.size.width-field4.frame.origin.x, field4.frame.size.height)];
        seletView1.delegate = self;
        [mainScroll addSubview:seletView1];
        [seletView1 setViewType:YDL_Type];
        [seletView1 setCurrentType:1];
        
        //选择孕期
        seletView2 = [[PerfectSelectView alloc] initWithFrame:seletView1.bounds];
        seletView2.delegate = self;
        [mainScroll addSubview:seletView2];
        [seletView2 setViewType:YQ_TYpe];
        [seletView2 setCurrentType:1];
        [seletView2 setCenter:CGPointMake(seletView1.center.x, seletView2.frame.size.height/2+seletView1.frame.size.height+5+seletView1.frame.origin.y)];
        
        //选择末次月经
        field5 = [[TextFieldView alloc] init];
        [field5 setBgImage:@"输入框.png" titleImage:@"完善资料页-末次月经icon.png" tip:@"末次月经"];
        [mainScroll addSubview:field5];
        [field5 setCenter:CGPointMake(label1.center.x, seletView2.frame.size.height+seletView2.frame.origin.y+10+field5.frame.size.height/2)];
        
        UIButton *button5 = [UIButton buttonWithType:UIButtonTypeCustom];
        [button5 setFrame:field5.frame];
        [mainScroll addSubview:button5];
        [button5 addTarget:self action:@selector(selectMCYJ) forControlEvents:UIControlEventTouchUpInside];
        
        //选择体重
        field6 = [[TextFieldView alloc] init];
        [field6 setBgImage:@"输入框.png" titleImage:@"完善资料页-孕前体重icon.png" tip:@"孕前体重"];
        [mainScroll addSubview:field6];
        [field6 setCenter:CGPointMake(label1.center.x, field5.frame.size.height+field5.frame.origin.y+10+field6.frame.size.height/2)];
        
        UIButton *button6 = [UIButton buttonWithType:UIButtonTypeCustom];
        [button6 setFrame:field6.frame];
        [mainScroll addSubview:button6];
        [button6 addTarget:self action:@selector(selectTZ) forControlEvents:UIControlEventTouchUpInside];
        
        doneButton = [OftenMenthod setButtonTitle:@"确认"];
        [mainScroll addSubview:doneButton];
        [doneButton addTarget:self action:@selector(doneButt) forControlEvents:UIControlEventTouchUpInside];
        [doneButton setCenter:CGPointMake(seletView2.center.x, field6.frame.size.height+field6.frame.origin.y+31+doneButton.frame.size.height/2)];
        
        [mainScroll setContentSize:CGSizeMake(0, doneButton.frame.size.height+doneButton.frame.origin.y+10)];
    }
    return self;
}

-(void)showTZInput:(BOOL)show
{
    if (show) {
        [field5 setHidden:NO];
        [field6 setHidden:NO];
        [doneButton setCenter:CGPointMake(seletView2.center.x, field6.frame.size.height+field6.frame.origin.y+31+doneButton.frame.size.height/2)];
        [mainScroll setContentSize:CGSizeMake(0, doneButton.frame.size.height+doneButton.frame.origin.y+10)];
    }else{
        [field5 setHidden:YES];
        [field6 setHidden:YES];
        [doneButton setCenter:CGPointMake(seletView2.center.x, seletView2.frame.size.height+seletView2.frame.origin.y+31+doneButton.frame.size.height/2)];
        [mainScroll setContentSize:CGSizeMake(0, doneButton.frame.size.height+doneButton.frame.origin.y+10)];
    }
}

//键盘消失
-(void)bgButt
{
    [field1.textField resignFirstResponder];
}

-(void)upHeadButt
{
    CLog(@"上传头像");
    UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:nil
                                                    delegate:self
                                           cancelButtonTitle:@"取消"
                                      destructiveButtonTitle:@"拍照"
                                           otherButtonTitles:@"从相册选择",nil];
    [sheet showInView:self];
}

-(void)getSelectView:(NSInteger)type
{
    [self bgButt];
    NSString *text = nil;
    if (selectField.textField.text.length==0) {
        if ([selectField isEqual:field2]) {
            text = @"1985-01-01";
        }else if ([selectField isEqual:field3]){
            text = [NSString stringWithFormat:@"160%@",APP_LENGTH_UNIT];
        }else if ([selectField isEqual:field4]){
            text = @"汉族";
        }else if ([selectField isEqual:field5]){
            NSString *date = [z_DateTime encodeTime:[NSDate date] format:APP_SELECTPICKERVIEW_DATE_FORMAT];
            NSRange range;
            range.length = 2;
            range.location = date.length-2;
            text = [date stringByReplacingCharactersInRange:range withString:@"01"];
        }else{
            text = [NSString stringWithFormat:@"50.0%@",APP_WEIGHT_UNIT];
        }
    }else{
        text = selectField.textField.text;
    }
    UIView *view = self.superview;
    SelectPickerView *dateView = [[SelectPickerView alloc] initWithFrame:view.bounds];
    [dateView setDelegate:self];
    [dateView setShowView:type text:text];
    [view addSubview:dateView];
}

-(void)selectCSRQ
{
    CLog(@"选择出生日期");
    selectField = field2;
    [self getSelectView:CSRQ_TYPE];
}

-(void)selectSG
{
    CLog(@"选择身高");
    selectField = field3;
    [self getSelectView:SG_YF_TYPE];
}

-(void)selectMZ
{
    CLog(@"选择民族");
    selectField = field4;
    [self getSelectView:XZMZ_TYPE];
}

-(void)selectMCYJ
{
    CLog(@"选择末次月经");
    selectField = field5;
    [self getSelectView:MCYJ_TYPE];
}

-(void)selectTZ
{
    CLog(@"选择体重");
    selectField = field6;
    [self getSelectView:YQTZ_TYPE];
}

-(void)doneButt
{
    if ([field1.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length==0) {
        [LoadingFrameView autoDisappearTipview:@"请输入您的昵称"];
    }else if (field2.textField.text.length==0){
        [LoadingFrameView autoDisappearTipview:@"请选择您的出生日期"];
    }else if (field3.textField.text.length==0){
        [LoadingFrameView autoDisappearTipview:@"请选择您的身高"];
    }else if (field4.textField.text.length==0){
        [LoadingFrameView autoDisappearTipview:@"请选择您的民族"];
    }else if (field5.textField.text.length==0 && seletView2.currentType!=0){
        [LoadingFrameView autoDisappearTipview:@"请选择您的末次月经时间"];
    }else if (field6.textField.text.length==0 && seletView2.currentType!=0){
        [LoadingFrameView autoDisappearTipview:@"请选择您的孕前体重"];
    }else {
        CLog(@"完成注册");
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
        [dic setValue:IOS_COMPLETE forKeyPath:IOS_METHOD_NAME];
//        [dic setValue:@"6" forKey:@"id"];
        [dic setValue:APP_USER_MSG.id forKey:@"id"];
        if (headButton.layer.cornerRadius >0) {
            [dic setValue:[self getImagePath] forKey:@"headimg"];
        }else{
            [dic setValue:@"" forKey:@"headimg"];
        }
        [dic setValue:field1.textField.text forKey:@"nickname"];
        [dic setValue:field2.textField.text forKey:@"birthday"];
        [dic setValue:field3.textField.text forKey:@"height"];
        [dic setValue:[NationClass getNameID:field4.textField.text] forKey:@"nation"];
        [dic setValue:[NSNumber numberWithInt:(seletView1.currentType+1)] forKey:@"amount"];
        [dic setValue:[NSNumber numberWithInt:(seletView2.currentType+1)] forKey:@"pregnancy"];
        CLog(@"%d===%d",seletView1.viewType,seletView2.viewType);
        if (seletView2.currentType!=0) {
            [dic setValue:field5.textField.text forKey:@"last_menstrual"];
            [dic setValue:field6.textField.text forKey:@"weight"];
        }else{
            [dic setValue:@"" forKey:@"weight"];
            [dic setValue:@"" forKey:@"last_menstrual"];
        }
    
        if ([(NSObject*)self.delegate respondsToSelector:@selector(done:)]) {
            [self.delegate done:dic];
        }
    }
}

#pragma mark - 图片处理
//保存图片到document
- (void)saveImage:(UIImage *)tempImage
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:IMAGE_NAME];
    [imageData writeToFile:fullPathToFile atomically:NO];
}
- (NSString *)documentFolderPath
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}

//获取图片路径
-(NSString*)getImagePath
{
    return [[self documentFolderPath] stringByAppendingPathComponent:IMAGE_NAME];
}

#pragma mark - PerfectSelectViewDelegate
-(void)selectIndex:(NSInteger)index view:(PerfectSelectView *)view
{
    if (view.viewType == YQ_TYpe) {
        CLog(@"选中了孕期的%d项",index);
        if (index == 0) {
            //
            CLog(@"去掉体重");
            [self showTZInput:NO];
        }else{
            if (index == 1 && seletView1.currentType!=0) {
                [seletView1 setCurrentType:0];
            }
            CLog(@"显示体重");
            [self showTZInput:YES];
        }
    }else{
        CLog(@"选中了运动量的%d项",index);
        if (seletView2.currentType == 1 && seletView1.currentType != 0) {
            seletView1.currentType = 0;
        }
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([textField isEqual:field1.textField]) {
        //最大字符个数
        NSInteger MAX_CHARS = 15;
        
        NSMutableString *newtxt = [NSMutableString stringWithString:textField.text];
        [newtxt replaceCharactersInRange:range withString:string];
        
        return ([newtxt length] <= MAX_CHARS);
    }else{
        return NO;
    }
}

#pragma mark - SelectPickerViewDelegate
//选择的时间
-(void)selectedText:(NSString*)text
{
    CLog(@"选中的=====%@",text);
    selectField.textField.text = text;
}

#pragma mark - 添加照片
//UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            //拍照
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                picker.delegate = self;
                picker.allowsEditing = YES;
            }
            [UIVC presentViewController:picker animated:YES completion:nil];
            
        }
            break;
        case 1:
        {
            //从相册选择
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            [picker setDelegate:self];
            [UIVC presentViewController:picker animated:YES completion:nil];
        }
            break;
        case 2:
        {
            //取消
        }
            break;
        default:
            break;
    }
}

#pragma mark - UIImagePickerControllerDelegate 用户选中图片后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        //压缩图片
        UIImage *theImage = [self fitSmallImage:image];
        //保存图片到本地
        [self saveImage:theImage];
        dispatch_async(dispatch_get_main_queue(), ^{
            [headButton setImage:theImage forState:UIControlStateNormal];
            [headButton setImage:theImage forState:UIControlStateHighlighted];
            [headButton.layer setCornerRadius:MIN(headButton.frame.size.height, headButton.frame.size.width)/2];
            [headButton.layer setMasksToBounds:YES];

            [UIVC dismissViewControllerAnimated:YES completion:nil];
        });
    });
}

//图片等比例压缩
-(UIImage *)fitSmallImage:(UIImage *)image
{
    if (nil == image){
        return nil;
    }
    
    if (image.size.width<IMAGE_MAX_SIZE_WIDTH){
        return image;
    }
    
    CGSize size = [self fitsize:image.size];
    UIGraphicsBeginImageContext(size);
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    [image drawInRect:rect];
    UIImage *newing = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newing;
}
- (CGSize)fitsize:(CGSize)thisSize
{
    if(thisSize.width == 0 && thisSize.height ==0)
        return CGSizeMake(0, 0);
    CGFloat wscale = thisSize.width/IMAGE_MAX_SIZE_WIDTH;
    CGSize newSize = CGSizeMake(thisSize.width/wscale, thisSize.height/wscale);
    return newSize;
}

@end
